package com.htc.dlc.fragment;
import java.util.ArrayList;
import java.util.List;

import com.htc.adapter.NewsAdapter;
import com.htc.common.ActionEvent;
import com.htc.constants.Constants;
import com.htc.controller.NewsModelController;
import com.htc.dlc.DetailNewsActivity;
import com.htc.dlc.R;
import com.htc.dlc.SettingsActivity;
import com.htc.model.dto.NewsModuleDTO;
import com.htc.slidingmenu.library.PageIndicator;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;

import com.htc.slidingmenu.library.CirclePageIndicator;

public class FragmentHome extends Fragment implements OnItemClickListener {
	NewsAdapter adapter;
	ArrayList<Object> arrData;
	ListView lv_home;
	ViewPager mPager;
	View header;

	Handler handler;
	public static final int DELAY = 5000;
	PageIndicator mIndicator;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_home, container,
				false);
		lv_home = ((ListView) rootView.findViewById(R.id.lv_home));
		header = getActivity().getLayoutInflater().inflate(
				R.layout.activity_slishow, null);
		View footer = getActivity().getLayoutInflater().inflate(
				R.layout.activity_footer, null);
		lv_home.addHeaderView(header);
		lv_home.addFooterView(footer);
		mPager = (ViewPager) header.findViewById(R.id.pager);
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int height = displaymetrics.heightPixels;
		mPager.getLayoutParams().height = height*1/3;
		mIndicator = (CirclePageIndicator) header.findViewById(R.id.indicator);
		lv_home.setOnItemClickListener(this);
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		ImagePagerAdapter adapterimg = new ImagePagerAdapter();
		mPager.setAdapter(adapterimg);
		mIndicator.setViewPager(mPager);

		handler = new Handler();
		handler.removeCallbacks(incrementPage);
		handler.postDelayed(incrementPage, DELAY);
		arrData = new ArrayList<Object>();
		adapter = new NewsAdapter(getActivity(), R.layout.adapter_news, arrData);
		lv_home.setAdapter(adapter);
		initData1();
		
		mPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int postion) {
				mIndicator.setViewPager(mPager, postion);
				
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});

	}

	private void initData1() {
		ActionEvent e = new ActionEvent(this, Constants.GET_NEWS_MODEL, null,
				null);
		NewsModelController.getInstance().handleViewEvent(e);
	}

	@SuppressWarnings("unchecked")
	public void handleControllerViewEvent(ActionEvent e) {
		switch (e.action) {
		case Constants.GET_NEWS_MODEL:
			ArrayList<NewsModuleDTO> newArr = (ArrayList<NewsModuleDTO>) e.viewData;
			new VerySlowTask(newArr).execute();
			break;
		default:
			break;
		}
	}

	public class VerySlowTask extends AsyncTask<String, Object, Void> {
		List<NewsModuleDTO> _newArr;

		public VerySlowTask(List<NewsModuleDTO> arr) {
			_newArr = arr;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			for (int i = 0; i < _newArr.size(); i++) {
				publishProgress(_newArr.get(i));

			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Object... values) {
			arrData.add(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			adapter.notifyDataSetChanged();
		}

	}

	private Runnable incrementPage = new Runnable() {

		@Override
		public void run() {
			int currentItem = mPager.getCurrentItem();

			int maxItems = mPager.getAdapter().getCount();

			if (maxItems != 0) {

				mPager.setCurrentItem((currentItem + 1) % maxItems, true);

			} else {

				mPager.setCurrentItem(0, true);

			}

			handler.postDelayed(incrementPage, DELAY);

		}
	};

	private class ImagePagerAdapter extends PagerAdapter {
		private int[] mImages = new int[] { R.drawable.home1, R.drawable.home2,
				R.drawable.home3, R.drawable.home4, R.drawable.home5 };

		@Override
		public int getCount() {
			return mImages.length;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			Context context = getActivity();
			ImageView imageView = null;
			try {
				imageView = new ImageView(context);
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				imageView.setImageResource(mImages[position]);

				((ViewPager) container).addView(imageView, 0);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			return imageView;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((ImageView) object);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return (view == object);
		}

		/**
		 * Called when the a change in the shown pages has been completed. At
		 * this point you must ensure that all of the pages have actually been
		 * added or removed from the container as appropriate.
		 * 
		 * @param arg0
		 *            The containing View which is displaying this adapter's
		 *            page views.
		 */
		@Override
		public void finishUpdate(ViewGroup arg0) {
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(ViewGroup arg0) {
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(adapter.getArrObject().size() >= 1){
			//Object o = adapter.getArrObject().get(position);
			NewsModuleDTO dto = null;
			try {
				dto = (NewsModuleDTO) lv_home.getItemAtPosition(position);
				Intent intent = new Intent(getActivity(), DetailNewsActivity.class);
				Bundle data = new Bundle();
				SettingsActivity st = new SettingsActivity();
				if (st.flag == 0) {
					data.putString("title", dto.getNewsModuleTitle());
					data.putString("description", dto.getNewsModuleDescription());
				} else if (st.flag == 1) {
					data.putString("title", dto.getNewsModuleTitleAr());
					data.putString("description", dto.getNewsModuleDescriptionAr());
				}

				data.putString("image", dto.getNewsModuleImage());
				intent.putExtras(data);
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		

	}

}
